<template>
	<view class="min-vh-70">
		<view class="x-navbar x-navbar-sticky x-navbar-body"
			:style="[`--bg-opacity:${opacity.navbar}`, `padding-top:${PLATFORM.statusBarHeight}px`]">
			<view class="x-navbar-tools grid-gap-2">
				<x-city class="font-weight-500 h8 text-ellipsis-1" style="max-width:calc(100% - 15px)" />
				<image src="/static/icons/arrow-down.png" mode="aspectFit" class="x-navbar-icons-image"
					style="width: 7px; height: 6px;" />
			</view>
			<view class="x-navbar-content">
				<text class="text-primary h6 font-weight-700 text-ellipsis-1 x-navbar-title">{{
					WebConfigStore.replaceIndustryPersonnelName('技师') }}</text>
			</view>
			<view class="x-navbar-icons"></view>
			<!-- #ifndef MP-WEIXIN -->
			<view class="x-navbar-icons" @tap="toggleShowMap">
				<image src="/static/icons/list-icon.png" mode="aspectFit" class="x-navbar-icons-image"
					style="width: 34px; height: 34px;" v-if="showMap" />
				<image src="/static/icons/map-icon.png" mode="aspectFit" class="x-navbar-icons-image"
					style="width: 34px; height: 34px;" v-else />
			</view>
			<!-- #endif -->
			<!-- #ifdef MP-WEIXIN -->
			<view class="x-navbar-icons"></view>
			<!-- #endif -->
		</view>
		<view class="x-search"
			:style="[`--bg-opacity:${opacity.navbar}`, `--xl-status-bar-height:${PLATFORM.statusBarHeight}px`]">
			<view class="x-search-input">
				<image src="/static/icons/search.png" mode="aspectFit" style="width: 16px; height: 16px;" />
				<input type="text" class="x-search-input__content" placeholder="搜索" placeholder-class="text-placeholder"
					confirm-type="search" v-model="search.keywords" @input="searchGetList" />
				<text class="x-search-input__btn" @tap="searchGetList">搜索</text>
			</view>
			<!-- #ifdef MP-WEIXIN -->
			<view class="x-search-icons" @tap="toggleShowMap">
				<image src="/static/icons/list-icon.png" mode="aspectFit" class="x-navbar-icons-image"
					style="width: 34px; height: 34px;" v-if="showMap" />
				<image src="/static/icons/map-icon.png" mode="aspectFit" class="x-navbar-icons-image"
					style="width: 34px; height: 34px;" v-else />
			</view>
			<view class="x-mp-weixin-capsule"></view>
			<!-- #endif -->
		</view>
		<view v-if="showMap" :style="[`--xl-status-bar-height:${PLATFORM.statusBarHeight}px`]">
			<!-- #ifdef H5 -->
			<view id="container" class="map-container"></view>
			<x-loading v-if="loadingMap" />
			<!-- #endif -->
			<!-- #ifdef MP-WEIXIN || APP -->
			<map id="container" class="map-container" show-location :markers="markers" :longitude="centerMap.longitude"
				:latitude="centerMap.latitude" @regionchange="mapMoved" @markertap="clickMarker">
			</map>
			<!-- #endif -->
			<view class="technician-item flex flex-center" v-if="technician.technician_id">
				<view class="flex-1 bg-white rounded-4 p-4">
					<x-technician-item :item="technician" />
				</view>
			</view>
		</view>
		<view class="p-4 flex flex-column grid-gap-4" v-else>
			<view class="bg-white rounded-4 p-4" v-for="(item, index) in list" :key="index">
				<x-technician-item :item="item" />
			</view>
			<x-more :status="loading" @load="getList"></x-more>
			<x-one-click-alarm ref="XOneClickAlarmRef"/>
		</view>
		<x-tabbar @reload="handleReload"></x-tabbar>
	</view>
</template>

<script setup lang="ts">
import { ref, watch, watchEffect, nextTick,onBeforeUnmount } from 'vue';
import { $func, $api, $helper, $page } from '@/utils';
import { $EventName } from '@/utils/const/env';
import { onPageScroll, onLoad,  onReachBottom, onShow,onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';
import { usePlatformStore, useWebConfigStore, useStatusStore, useRefs } from "@/stores";
import { useMap } from "@/utils/map";
let map: any, mapContainer: any, appMap: any;
const PlatformStore = usePlatformStore();
const { PLATFORM } = useRefs(PlatformStore);
const WebConfigStore = useWebConfigStore();
const StatusStore = useStatusStore();
const { GLOBALSTATUS } = useRefs(StatusStore);
const opacity = ref<{
	navbar: number | string
	search: number | string
}>({
	navbar: 0,
	search: 0,
});
const top = ref(0);
watch(() => top.value, (val: number) => {
	if (val < -10) {
		return;
	}
	opacity.value.navbar = val > 50 ? 1 : (val / 50).toFixed(1);
	opacity.value.search = val > (50 + PLATFORM.value.statusBarHeight) ? 1 : (val / (50 + PLATFORM.value.statusBarHeight)).toFixed(1);
	if (val < 10) {
		list.value = list.value.sort((a: any, b: any) => a.sort - b.sort);
	}
})
const search = ref({
	page: 1,
	limit: 10,
	keywords: '',
	sort: 'recommend',
	order: 'desc'
})
watchEffect(() => {
	if (GLOBALSTATUS.value?.location) {
		search.value.latitude = GLOBALSTATUS.value.location.latitude;
		search.value.longitude = GLOBALSTATUS.value.location.longitude;
	}
})
const loading = ref<LoadingType>('loadmore');
const list = ref<any[]>([]);
const getList = () => {
	if (loading.value === 'loading' || loading.value === 'nomore') return;
	loading.value = 'loading';
	$api.Technician.list(search.value).then((data: any) => {
		loading.value = 'loadmore';
		const d = data.data.sort((a: any, b: any) => a.sort - b.sort);
		list.value = [...list.value, ...d];
		search.value.page++;
		if (data.current_page >= data.last_page) {
			loading.value = 'nomore';
		}
	}).finally(() => {
		if (loading.value === 'loading') {
			loading.value = 'loadmore';
		}
	});
}
const debounceGetList = $func.debounce(getList, 300);
const searchGetList = () => {
	loading.value = 'loadmore';
	search.value.page = 1;
	list.value = [];
	debounceGetList();
}

const loadingMap = ref(false)
const showMap = ref(false);
const technician = ref({
	technician_id: ''
})
const searchMap = ref({
	latitude: 0,
	longitude: 0
})
const centerMap = ref({
	latitude: 0,
	longitude: 0
})
let zIndex = 100;
let listMap: any[] = [];
const getListMap = () => {
	if (loadingMap.value) return;
	loadingMap.value = true;
	// #ifdef APP
	uni.showLoading({ title: '加载中...' });
	// #endif
	$api.Technician.list({
		...search.value,
		...searchMap.value,
		page: 0,
		limit: 1000
	}).then((data: any) => {
		listMap = data;
		// #ifdef H5
		zIndex++;
		// 清除地图上的所有覆盖物
		mapContainer.clearMap();
		const labelMarkers = listMap.map((item: any) => {
			const labelMarker = new map.AMap.LabelMarker({
				name: item.technician_id,
				position: [item.longitude, item.latitude],
				zooms: [10, 20],
				opacity: 1,
				zIndex: 2,
				icon: {
					image: `/app/ycMassage/static/icons/location-${item.gender}.png`,
					anchor: 'bottom-center',
					size: [32, 32]
				}
			});
			labelMarker.on('click', () => {
				technician.value = item;
			})
			return labelMarker;
		}).filter((item: any) => item);
		const labelsLayer = new map.AMap.LabelsLayer({
			zIndex
		});
		labelsLayer.add(labelMarkers);
		mapContainer.add(labelsLayer);
		// #endif
		// #ifdef MP-WEIXIN || APP
		initMarkers();
		// #endif
	}).finally(() => {
		loadingMap.value = false;
		// #ifdef APP
		uni.hideLoading();
		// #endif
	});
}
const debounceGetListMap = $func.debounce(getListMap, 300);
const initAMap = () => {
	showMap.value = true;
	// #ifdef H5
	nextTick(() => {
		map.createMap("container").then((res: any) => {
			mapContainer = res;
			res.on('complete', () => {
				map.usePlugin('ToolBar', {
					offset: [10, 70],
					position: 'RT'
				}).then((toolBar: any) => {
					mapContainer.addControl(toolBar);
				}).catch((err: any) => { console.log(err) })
				mapContainer.on('click', (e: any) => {
					technician.value = {};
					mapContainer.setCenter([e.lnglat.lng, e.lnglat.lat]);
				});
				mapContainer.on('moveend', () => {
					if (loadingMap.value) { return; }
					technician.value = {};
					const Bounds = mapContainer.getBounds();
					// 视图的中心点坐标
					const center = mapContainer.getCenter();
					searchMap.value.latitude = center.lat;
					searchMap.value.longitude = center.lng;
					searchMap.value.range = Bounds.getSouthWest().distance(Bounds.getNorthEast());
					debounceGetListMap();
				});
				map.getCurrentPosition().then((result: any) => {
					mapContainer.setCenter([result.position.lng, result.position.lat]);
				}).catch((err: any) => {
					console.log(err);
				});
			});
		}).catch((err: any) => {
			console.log(err);
		});
	})
	// #endif

	// #ifdef MP-WEIXIN || APP
	nextTick(() => {
		if (mapContainer) return initMarkers();
		uni.showLoading({ title: '定位中...' });
		map.createMap("container").then((res: any) => {
			map.getCurrentPosition({
				altitude: false,
				geocode: false,
				isHighAccuracy: false
			}).then((result: any) => {
				console.log(result);
				nextTick(() => {
					mapContainer = uni.createMapContext('container');
					centerMap.value.latitude = result.latitude;
					centerMap.value.longitude = result.longitude;
					// #ifdef APP
					appMap = mapContainer.$getAppMap();
					if (appMap) {
						var center = new plus.maps.Point(result.longitude, result.latitude);
						appMap.setCenter(center);
					}
					// #endif
					// #ifdef MP-WEIXIN
					searchMap.value.latitude = result.latitude;
					searchMap.value.longitude = result.longitude;
					debounceGetListMap();
					// #endif
				})
			}).catch((err: any) => {
				console.log(err);
			}).finally(() => {
				uni.hideLoading();
			})
		})
	})
	// #endif
}
// #ifdef MP-WEIXIN
const mapMoved = (e: any) => {
	if (e.type === 'end') {
		searchMap.value.latitude = e.detail.centerLocation.latitude;
		searchMap.value.longitude = e.detail.centerLocation.longitude;
		technician.value = {};
		debounceGetListMap();
	}
}
const clickMarker = (e: any) => {
	technician.value = {};
	nextTick(() => {
		const find = listMap.find((item: any) => item.technician_id === e.markerId);
		if (find) {
			technician.value = find;
		}
	})
}
// #endif
// #ifdef APP
const mapMoved = (e: any) => {
	console.log(e);
	if (appMap) {
		appMap.getCurrentCenter((state: any, res: any) => {
			if (state !== 0) return;
			searchMap.value.latitude = res.latitude;
			searchMap.value.longitude = res.longitude;
			technician.value = {};
			debounceGetListMap();
		})
	}
}
const clickMarker = (e: any) => {
	technician.value = {};
	nextTick(() => {
		const find = listMap.find((item: any) => item.technician_id === e.detail.markerId);
		if (find) {
			technician.value = find;
		}
	})
}
// #endif
// #ifdef MP-WEIXIN || APP
const markers = ref<any[]>([]);
const initMarkers = () => {
	nextTick(() => {
		technician.value = listMap[0] || {};
	})
	const markers = listMap.map((item: any) => {
		return {
			id: item.technician_id,
			latitude: item.latitude,
			longitude: item.longitude,
			width: 32,
			height: 32,
			iconPath: `/static/icons/location-${item.gender}.png`,
		}
	});
	// #ifdef APP
	listMap.forEach((item: any) => {
		const marker = new plus.maps.Marker(new plus.maps.Point(item.longitude, item.latitude));
		marker.setIcon(`/static/icons/location-${item.gender}.png`);
		appMap.addOverlay(marker);
	})
	// #endif
	// #ifdef MP-WEIXIN
	mapContainer.addMarkers({
		markers,
		clear: true,
		fail: (err: any) => {
			console.log(err);
		}
	})
	// #endif
}
// #endif

onPageScroll(({ scrollTop }: { scrollTop: number }) => {
	top.value = scrollTop;
})
const handleReload = () => {
	searchGetList();
}
onReachBottom(() => {
	getList();
})
const toggleShowMap = () => {
	if (showMap.value) {
		showMap.value = false;
		// #ifdef H5
		mapContainer && mapContainer.destroy();
		mapContainer = null;
		// #endif
	} else if (map && map.isReady()) {
		initAMap();
	}
}
const useInitMap = () => {
	map = useMap()
}
onLoad(() => {
	searchGetList();
	useInitMap();
	uni.$once($EventName.WEBCONFIG_READY, useInitMap)
	uni.$on($EventName.X_CITY_CHANGE, searchGetList);
})
onBeforeUnmount(() => {
	uni.$off($EventName.WEBCONFIG_READY, useInitMap);
	uni.$off($EventName.X_CITY_CHANGE, searchGetList);
	// #ifdef H5
	mapContainer && mapContainer.destroy();
	// #endif
})
const XOneClickAlarmRef = ref<any>();
onShow(()=>{
	XOneClickAlarmRef.value?.getList();
	$page.title(WebConfigStore.replaceIndustryPersonnelName('技师'));
	// #ifdef H5
	$helper.replaceUrlParam('appid', $helper.appid());
	// #endif
})
onShareAppMessage(()=>{
	return $page.shareMessage({
		title: WebConfigStore.replaceIndustryPersonnelName('技师'),
		path: `/pages/technician/index`
	})
})
onShareTimeline(()=>{
	return $page.shareTimeline({
		title: WebConfigStore.replaceIndustryPersonnelName('技师'),
		path: `/pages/technician/index`
	})
})
</script>

<style lang="scss">
/* #ifdef H5 */
uni-page[data-page="pages/technician/index"] {

	/* #endif */
	page {
		background: radial-gradient(circle at 15% 20%, var(--xl-primary) -100%, transparent 35%),
			radial-gradient(circle at 27% 5%, var(--xl-primary-light-3) -50%, transparent 30%),
			radial-gradient(circle at 85% 17%, var(--xl-primary-light-1) -50%, transparent 25%);
		background-repeat: no-repeat;
		background-position: top center;
		background-color: $uni-bg-color-grey;
		/* #ifdef H5 */
		background-attachment: fixed;
		/* #endif */
	}

	/* #ifdef H5 */
}

/* #endif */
</style>
<style lang="scss" scoped>
.map-container {
	/* #ifdef APP */
	padding: 0px;
	margin: 0px;
	width: 100%;
	height: calc(100vh - 390px - var(--status-bar-height) - constant(safe-area-inset-bottom));
	height: calc(100vh - 390px - var(--status-bar-height) - env(safe-area-inset-bottom));
	/* #endif */
	/* #ifndef APP */
	padding: 0px;
	margin: 0px;
	width: 100%;
	height: calc(100vh - 150px - var(--status-bar-height) - constant(safe-area-inset-bottom));
	height: calc(100vh - 150px - var(--status-bar-height) - env(safe-area-inset-bottom));
	/* #endif */
}

.technician-item {
	/* #ifdef APP */
	height: 200px;
	padding: 16px;
	box-sizing: border-box;
	/* #endif */
	/* #ifndef APP */
	position: fixed;
	left: 20px;
	bottom: calc(70px + constant(safe-area-inset-bottom));
	bottom: calc(70px + env(safe-area-inset-bottom));
	right: 20px;
	z-index: 100;
	/* #endif */
}
</style>